import React, { useState } from 'react';
import { useAuth } from '../contexts/AuthContext';

interface LoginProps {
  onSuccess: () => void;
  onForgotPassword: () => void;
  onSwitchToRegister: () => void;
}

const Login: React.FC<LoginProps> = ({ onSuccess, onForgotPassword, onSwitchToRegister }) => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState('');
  const { login } = useAuth();

  const validatePassword = (value: string) => {
    if (value.length < 6) {
      setError('密码长度不能少于6个字符');
    } else {
      setError('');
    }
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    if (password.length < 6) {
      setError('密码长度不能少于6个字符');
      return;
    }
    try {
      await login(email, password);
      onSuccess();
    } catch (err) {
      if (err instanceof Error) {
        setError(err.message);
      } else {
        setError('登录失败，请稍后重试。');
      }
    }
  };

  return (
    <form onSubmit={handleSubmit} className="space-y-4">
      <div>
        <label htmlFor="email" className="block text-sm font-medium text-gray-700">邮箱</label>
        <input
          type="email"
          id="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          className="mt-1 block w-full px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
          required
        />
      </div>
      <div>
        <label htmlFor="password" className="block text-sm font-medium text-gray-700">密码</label>
        <input
          type="password"
          id="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          onBlur={(e) => validatePassword(e.target.value)}
          className="mt-1 block w-full px-3 py-2 bg-white border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
          required
        />
      </div>
      {error && <p className="text-red-500 text-xs italic">{error}</p>}
      <button
        type="submit"
        className="w-full bg-gradient-to-r from-sky-400 to-cyan-300 text-white py-2 px-4 rounded-lg font-medium hover:from-sky-500 hover:to-cyan-400 focus:outline-none focus:ring-2 focus:ring-sky-400 focus:ring-offset-2 transition duration-150"
      >
        登录
      </button>
      <div className="mt-4 flex justify-between">
        <button
          type="button"
          onClick={onForgotPassword}
          className="text-sm text-gray-600 hover:text-sky-500 transition duration-150"
        >
          忘记密码？
        </button>
        <button
          type="button"
          onClick={onSwitchToRegister}
          className="text-sm font-medium text-sky-600 hover:text-sky-500 transition duration-150"
        >
          没有账号？点击注册
        </button>
      </div>
    </form>
  );
};

export default Login;